<template>
  <div class="role">
    <div class="role-page">
      <div class="role-page-content">
        <div class="role-page-form">
          <el-input
            style="width: 300px"
            placeholder="请输入内容"
            @change="refreshRoleList"
            @blur="refreshRoleList"
            :suffix-icon="Search"
            v-model="filterText"
          />

          <div class="role-page-form-right">
            <el-button type="primary" @click="onAdd" v-btnPermission="'btn-role-updata'">+ 新增</el-button>
          </div>
        </div>
        <!-- 内容 -->
        <div class="role-page-table">
          <Table :columns="tableColumns" :data-source="dataSource" :loading="loading" />
          <div class="role-page-pagination">
           <Pagination
              style="margin-left: auto"
              :key="pageSize + 'Pagination' + currentPage"
              :count="total"
              :page-size="pageSize"
              :pageNo="currentPage"
              @onPagechange="handlePageChange"
              @onSizechange="handleSizeChange"
            />
          </div>
        </div>
      </div>
      <updata ref="updataRef" :data-type="dataType"  @refresh="handlePageChange(currentPage)"/>
    </div>
  </div>
</template>

<script setup lang="ts">
import { Search } from '@element-plus/icons-vue';
import { ElForm, ElMessage, ElMessageBox } from 'element-plus';
import updata from './common/updata.vue';
import type { TableColumn } from '@/types/table';
import type { Role, RoleQuery } from '@/types/role';
import {getRoleList,deleteRole,disableRole,enableRole} from '@/api/clinic';

const loading = ref(false);
const dataSource = ref<Role[]>([
]); // 数据源
const updataRef = ref<InstanceType<typeof updata>>();
const total = ref(3); // 总条数
const dataType = ref(1); // 数据类型
const filterText = ref(''); // 搜索框内容
// 查询参数
const currentPage = ref(1);
const pageSize = ref(10);
const handlePageChange = (val: number) => {
  currentPage.value = val;
  refreshRoleList();
};
const handleSizeChange = (val: number) => {
  currentPage.value = 1;
  pageSize.value = val;
  refreshRoleList();
};
const tableColumns: TableColumn[] = [
  // {  type:"selection", width: 50,prop:'selection', label: '选择', fixed: 'left' },
  { prop: 'roleName', label: '角色名称', width: 200 ,},
  {
    prop: 'isEnabledText',
    label: '状态',
    type: 'tag',
  },
  { prop: 'updateBy', label: '修改人', width: 200 },
  { prop: 'updateTime', label: '修改时间', width: 200 },
  
  {
    prop: 'action',
    label: '操作',
    type: 'action',
    width: 150,
    componentProps: {
      fixed: 'right',
    },
    buttonGroup: [
      {
        label: '编辑',
        permissions: 'btn-role-edit',
        type: 'text',
        click: (row: Role) => {
          handleEdit(row);
        },
      },
      // {
      //   label: '权限设置',
      //   type: 'text',
      //   click: (row: Role) => {
      //     handlePermissionSetting(row);
      //   },
      // },
      {
        label: '启用',
        permissions: 'btn-role-enable',
        statusName: ['isEnabled'],
        status: '0', // 当状态为停用时显示启用按钮
        type: 'text',
        click: async (row: Role) => {
           let res = await enableRole({ roleId: row.roleId });
           if (res.code === '200') {
            ElMessage.success(res.msg);
            refreshRoleList();
          } else {
            //ElMessage.error(res.msg);
          }
        },
      },
      {
        label: '停用',
        statusName: ['isEnabled'],
        status: '1', // 当状态为启用时显示停用按钮
        permissions: 'btn-role-disable',
        type: 'text',
        color: '#D90000',
        click:async (row: Role) => {
          let res = await disableRole({ roleId: row.roleId });
           if (res.code === '200') {
            ElMessage.success(res.msg);
            refreshRoleList();
          } else {
            //ElMessage.error(res.msg);
          }
        },
      },
      {
        label: '删除',
        permissions: 'btn-role-del',
        type: 'text',
        color: '#D90000',
        click: async(row: Role) => {
          handleDeleteRole(row)
          
        },
      },
    ],
  },
];

//弹窗调用
const onAdd = () => {
  if (updataRef.value) {
    dataType.value = 0
    updataRef.value.open();
  }
};
const title = ref<string>('');
 


// 角色操作方法
const handleEdit = (row: Role) => {
  //console.log('编辑角色:', row);
  title.value = '编辑角色';
  if (updataRef.value) {
    dataType.value = 1
    updataRef.value.open1(row);
  }
};

// const handlePermissionSetting = (row: Role) => {
//   //console.log('权限设置:', row);
//   title.value = `设置角色权限 - ${row.roleName}`;
//   if (dialogRef.value) {
//     dialogRef.value.open();
//   }
// };

 

 

const refreshRoleList = async ()=> {
  loading.value = true;
  const data = {
    roleName: filterText.value,
    pageNo: currentPage.value,
    pageSize: pageSize.value,
  };
  const res = await getRoleList(data);
   if(res.code != '200'){
            //ElMessage.error(res.msg);
            return
        }
  res.data.list.forEach((item:any) => {
    item.isEnabledText = item.isEnabled == 1 ? '启用' : '停用';
  });
  loading.value = false;
  total.value = res.data.totalCount;
  dataSource.value = res.data.list;
  //console.log('获取角色列表:', res);
}
onMounted(refreshRoleList);
const handleDeleteRole = (row: Role) => {
  ElMessageBox.confirm(
    `确定要删除角色"${row.roleName}"吗？删除后无法恢复，且会影响已分配此角色的用户。`,
    '删除角色',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning',
      confirmButtonClass: 'el-button--danger',
    }
  )
    .then(async () => {
      try {
        //console.log('删除角色:', row);
        // 这里调用删除角色的 API
        // await deleteRole(row.roleId);
        let res = await deleteRole({ roleId: row.roleId });
        if (res.code === '200') {
          ElMessage.success(res.msg);
          refreshRoleList();
        } else {
          //ElMessage.error(res.msg);
        }
       
        
      } catch (error) {
        //console.error('删除角色失败:', error);
        ElMessage({
          type: 'error',
          message: '删除角色失败',
        });
      }
    })
    .catch(() => {
      // 用户取消删除
    });
};
</script>

<style lang="scss" scoped>
.role {
  height: 100%;
}
.role-dialog {
  width: 80%;
  margin: 0 auto;
}
.role-page {
  background: #fff;
  border-radius: 6px;
  height: 100%;
  .role-page-nav {
    display: flex;
    align-items: center;
    justify-content: left;
    border-radius: 4px;
    border-bottom: 1px solid #e7e7e7;
    .el-dropdown-link {
      background: rgba(22, 173, 164, 0.08);
      border-radius: 0px 0px 0px 0px;
      padding: 16px 21px;
      cursor: pointer;
      color: var(--el-color-primary) !important;
      display: flex;
      font-size: 16px;
      align-items: center;
    }
  }
  .role-page-content {
    padding: 10px 24px;
    height: calc(100% - 64px);
    .role-page-form {
      display: flex;
      align-items: center;
      .role-page-form-right {
        margin-left: auto;
      }
    }
    .role-page-table {
      margin-top: 22px;
      height: calc(100% - 68px);
    }
    .role-page-pagination {
      margin-top: 24px;
      display: flex;
      justify-content: right;
      
    }
  }
}
</style>
